package org.nerve.fs;

import org.nerve.fs.common.HexUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.MessageDigest;

/**
 * org.nerve.fs
 * Created by zengxm on 2015/10/8 0008.
 */
public abstract class AbstractDFileSystem implements DFileSystem {

	/**
	 * 获取文件的md5
	 * @param file
	 * @return
	 * @throws FileNotFoundException
	 */
	protected String md5HexOfFile(File file) throws FileNotFoundException {
		return md5HexOfInputStream(new FileInputStream(file));
	}

	/**
	 * 获取指定流的md5
	 * @param is
	 * @return
	 */
	protected String md5HexOfInputStream(InputStream is){
		try{
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.reset();
			byte[] buffer = new byte[1024];

			int read = -1;
			while ((read = is.read(buffer, 0, 1024)) > -1) {
				md5.update(buffer, 0, read);
			}
			return HexUtils.toHex(md5.digest());
		}catch(Exception e){
			System.err.println("error on digest md5:"+e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
}
